document.getElementById('loginBtn').addEventListener('click', function () {
    const username = document.getElementById('username').value;
    const studentId = document.getElementById('studentId').value;
    const password = document.getElementById('password').value;
    const confirmPassword = document.getElementById('confirmPassword').value;

    // 前端验证两次密码是否一致
    if (password!== confirmPassword) {
        showToast('两次输入的密码不一致', 'danger');
        return;
    }

    // 前端验证登录必要字段
    if (!username ||!studentId ||!password) {
        showToast('请填写用户名、学工号和密码', 'danger');
        return;
    }

    // 构造请求数据，不包含confirmPassword
    const formData = {
        username,
        studentId,
        password
    };

    // 显示加载状态
    const btn = this;
    const originalText = btn.innerHTML;
    btn.disabled = true;
    btn.innerHTML = '<i class="fa fa-spinner fa-spin mr-3"></i> 正在登录...';

    // 发送登录请求
    fetch("/login/check", {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            'Accept': 'application/json'
        },
        body: JSON.stringify(formData)
    })
   .then(response => {
        return response.json().then(data => {
            console.log('响应状态:', response.status);
            console.log('响应数据:', data);

            if (!response.ok) {
                throw new Error(data.message || `登录请求失败 (${response.status})`);
            }

            return data;
        });
    })
   .then(data => {
        showToast(data.message,'success');
        setTimeout(() => {
            window.location.href = data.url || "/";
        }, 2000);
    })
   .catch(error => {
        showToast(error.message, 'danger');
        console.error('登录错误:', error);
    })
   .finally(() => {
        btn.disabled = false;
        btn.innerHTML = originalText;
    });
});

// 显示提示框
function showToast(message, type = 'info') {
    // 移除已有的提示框
    const existingToasts = document.querySelectorAll('.toast');
    existingToasts.forEach(toast => toast.remove());

    const toast = document.createElement('div');
    toast.classList.add('toast', type);
    toast.innerHTML = `
        <div class="flex items-center">
            <i class="fa ${
                type ==='success'? 'fa-check-circle text-xl' :
                type === 'danger'? 'fa-exclamation-circle text-xl' :
                'fa-info-circle text-xl'
            } mr-3"></i>
            <span class="font-medium">${message}</span>
        </div>
    `;

    document.body.appendChild(toast);

    // 触发动画
    setTimeout(() => {
        toast.classList.add('show');
    }, 10);

    // 自动关闭
    setTimeout(() => {
        toast.classList.remove('show');
        setTimeout(() => {
            toast.remove();
        }, 300);
    }, 3000);
}